package com.shwread.httpsdk.http.base;

import android.content.Context;

import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.util.NetUtil;
import com.shwread.httpsdk.util.Util;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import logic.constants.Const;


/**
 * @Title: AbstractHttpPostForByte.java
 * @Package com.surfingread.httpsdk.http.base
 * @Description: TODO(添加描述)
 * @author 刘章
 * @date 2014年2月7日 下午1:50:27
 */
public abstract class AbstractHttpPostForByte
        extends
        AbstractHttpBase
{
	private HttpClient   httpClient;
	//private DefaultHttpClient httpClient;
	private HttpPost     requestPost;
	private HttpResponse response;
	private String       resultCode;
	private String       timeStamp;
	private String 		 action;
	private HashMap<String, String> parameter_map = new HashMap<String, String>();
	
	public AbstractHttpPostForByte(Context context,String action, ActionListener actionListener) {
		super(context,action, actionListener);
		this.action = action;
	}
	
	protected abstract void getParameter(HashMap<String, String> parameter_map);
	
	protected abstract byte[] getRequsetByte();
	
	public abstract void doResponseXml(int resultCode, String TimeStamp, String xml);
	
	public String getUrl() {
		String result = "";
		getParameter(parameter_map);
		if (parameter_map != null && !parameter_map.isEmpty())
		{
			result += "?";
			Iterator<Entry<String, String>> it = parameter_map.entrySet().iterator();
			while (it.hasNext())
			{
				Entry<String, String> entry = it.next();
				result += entry.getKey() + "=" + entry.getValue() + "&";
			}
			result = result.substring(0, result.length() - 1);
		}
		println("请求URL：" + Const.SERVER_URL + "/" + action + result);
		return Const.SERVER_URL + "/" + action + result;
	}
	
	@Override
	protected void doHttp() {
		try
		{
			httpClient = new DefaultHttpClient(params);
			
			requestPost = new HttpPost(URI.create(getUrl()));
			Iterator<Entry<String, String>> it = getHeader().entrySet().iterator();
			while (it.hasNext())
			{
				Entry<String, String> entry = it.next();
				println("key:" + entry.getKey() + " value:" + entry.getValue());
				requestPost.addHeader(entry.getKey(), entry.getValue());
			}
			byte[] bt = getRequsetByte();
			InputStream instream = new ByteArrayInputStream(bt);
			InputStreamEntity inputStreamEntity = new InputStreamEntity(instream, bt.length);
			requestPost.setEntity(inputStreamEntity);
			
			//ArrayList<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>();
			//requestPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, HTTP.UTF_8));
			
			response = httpClient.execute(requestPost);
			for (Header header : response.getAllHeaders())
			{
				println("[header]:" + header.getName() + " " + header.getValue());
			}
			int code = response.getStatusLine().getStatusCode();
			println("code:" + code);
			if (code == HttpStatus.SC_OK)
			{
				try
				{
					resultCode = response.getFirstHeader("result-code").getValue();
				}
				catch (NullPointerException e)
				{
					
				}
				try
				{
					timeStamp = response.getFirstHeader("TimeStamp").getValue();
				}
				catch (NullPointerException e)
				{
					
				}
				doResponseXml(Integer.parseInt(Util.isEmpty(resultCode) ? "-1" : resultCode), timeStamp, new String(EntityUtils.toByteArray(response.getEntity()), Const.charset));
			}
			else
			{
				HTTPERROR(code,null);
			}
		}
		catch (Exception e)
		{
			HTTPERROR(NetUtil.NetError,e);
		}
		finally
		{
			DoDispose();
		}
	}
	
	private void DoDispose() {
		if (response != null)
		{
			response = null;
		}
		if (requestPost != null)
		{
			requestPost.abort();
		}
		if (httpClient != null)
		{
			//httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
		if (header_map != null)
		{
			header_map.clear();
			header_map = null;
		}
		if (listener != null)
		{
			listener = null;
		}
		dispose();
		context = null;
	}
}
